<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']">
            新增内置账户
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button :disabled="multiple" type="primary" icon="el-icon-delete" size="mini" @click="handleDelete">
            批量删除
          </el-button>
        </el-col>
          <el-col :span="1.5" v-if="productNameKey">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="cookieUpdateVal" v-hasPermi="['system:user:add']">
                  定时更新配置
              </el-button>
          </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column show-overflow-tooltip label="编码" align="center" width="100" prop="code"/>
<!--        <el-table-column label="客户端" align="center" prop="client" :show-overflow-tooltip="true"/>-->
        <el-table-column label="账号" align="center" prop="username" :show-overflow-tooltip="true"/>
        <el-table-column label="密码" align="center" prop="password" :show-overflow-tooltip="true"/>
        <el-table-column label="cookie" align="center" prop="cookie" :show-overflow-tooltip="true"/>
<!--        <el-table-column label="备用cookie" align="center" prop="backUpCookie" :show-overflow-tooltip="true"/>-->
        <el-table-column label="更新时间" align="center" prop="updateTime" :show-overflow-tooltip="true"/>
        <el-table-column label="在线使用人数" align="center" prop="onlineUser" :show-overflow-tooltip="true"/>
        <el-table-column label="状态" align="center" width="80" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <span v-if = 'scope.row.available === 0' style="color: red" >
                <i class="el-icon-circle-close"/>
            </span>
            <span v-else-if = 'scope.row.available === 1' style="color: green">
                <i class="el-icon-circle-check"/>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="设置" align="center" width="200" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-refresh" @click="updateUserCookie(scope.row)"
                       v-hasPermi="['system:user:edit']">刷新
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['system:user:edit']">设置
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
            </el-button>
            <!--              <el-button size="mini" type="text" icon="el-icon-key" @click="handleResetPwd(scope.row)" v-hasPermi="['system:user:resetPwd']">重置</el-button>-->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </el-row>

    <!-- 新增或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号" prop="username">
              <el-input  v-model="form.username" placeholder="请输入账号"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入密码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="编码" prop="code">
              <el-input v-model="form.code" placeholder="请输入编码"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="cookie" prop="cookie">
              <el-input v-model="form.cookie" placeholder="请输入cookie"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备用cookie" prop="backUpCookie">
              <el-input v-model="form.backUpCookie" placeholder="请输入备用cookie"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="showCookie" width="500px" append-to-body center>
      <el-form ref="form" label-width="140px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="定时配置更新(分钟)" prop="username">
              <el-input  v-model="cookieVal" placeholder="定时配置更新"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitCookieUpdateTime">保 存</el-button>
          <el-button @click="showCookie = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    delUser,
    resetUserPwd,
    updateUserCookie,
    updateUserCookieM,
    updateUserCookieJsPlugin,
    updateUserCookieElves,
    getCookieRefresh,
    setCookieRefresh
  } from "@/api/system/user";
  import {getToken} from "@/utils/auth";
  import { listData, addClient, updateClient } from "@/api/setClient/index"

  export default {
    name: "User",
    data() {
      return {
        productId: '', //首页跳转过来的ID
        productName: '', //首页跳转过来的Name
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        userList: []
        ,
        // 弹出层标题
        title: "",
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        //分配弹框
        showConfig:false,
        // 部门名称
        deptName: undefined,
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        // 性别状态字典
        sexOptions: [],
        // 岗位选项
        postOptions: [],
        // 角色选项
        roleOptions: [],
        // 表单参数
        form: {
          productName: '', //应用名称
          username: '', //账户
          password: '', //密码
          code:'',
          cookie: '', //cooike
          productUrl: '', //地址
          salt: '',
          backUpCookie:'',
          productId: ''
        },
        defaultProps: {
          children: "children",
          label: "label",
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/user/importData",
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        // 表单校验
        rules: {
          username: [
            {required: true, message: "请输入账户名", trigger: "blur"},
          ],
          productUrl: [
            {required: true, message: "请输入应用URL地址", trigger: "blur"},
          ],
          password: [
            {required: true, message: "请输入密码", trigger: "blur"},
          ],
          productName: [
            {required: true, message: "请输入应用名称", trigger: "blur"},
          ],
          cookie: [
            {required: false, message: "请输入应用名称", trigger: "blur"},
          ],
          code:[
            {required: true, message: "请输入编码", trigger: "blur"},
          ]
        },
        cookieVal: '',
        showCookie: false,
        mapK: {
          'merchantwords': 'COOKIE_REFRESH_TIME_INTERVAL',
          'junglescout': 'JUNGLE_SCOUT_COOKIE_REFRESH_TIME_INTERVAL',
          ['js插件']: 'JS_PLUGIN_COOKIE_REFRESH_TIME_INTERVAL',
          ['卖家精灵']:'',
        }
      };
    },
    watch: {
      // 根据名称筛选部门树
      deptName(val) {
        this.$refs.tree.filter(val);
      },
    },
    beforeRouteEnter(to, from, next) {
      next(vm => {
        vm.productId = to.query.productId
        vm.productName = to.query.productName
        vm.form.productId = to.query.productId
        vm.getList()
      })
    },
    computed: {
      productNameKey() {
        return this.mapK[this.productName] || ''
      }
    },
    created() {
      // this.getList();
    },
    methods: {
      /** 查询用户列表 */
      getList() {
        this.loading = true;
        let { pageSize, pageNum } = this.queryParams
        let parm = {
          id: this.productId,
          pageSize: pageSize,
          pageNum: pageNum
        }
        listData(parm).then(
          (resp) => {
            let { code, rows } = resp
            if(code === 200) {
              this.userList = rows
            }
            this.total = resp.total;
            this.loading = false;
          }
        );
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          productName: '', //应用名称
          username: '', //账户
          password: '', //密码
          cookie: '', //cooike
          productUrl: '', //地址
          salt: '',
          productId: this.productId
        };
        this.resetForm("form");
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "新增内置账户";
      },
      /** cookie更新时间按钮操作 */
      cookieUpdateVal() {
        this.cookieVal = ''
        this.showCookie = true;
        this.title = "定时更新配置";
        this.getCookieRefresh()
      },
      async getCookieRefresh () {
        try {
          const {data, code} = await getCookieRefresh(this.productNameKey)
          if(code === 200) {
            this.cookieVal = data
          }
        }catch (e) {
          console.log(e)
        }
      },
      async submitCookieUpdateTime () {
        try {
          if(!this.cookieVal) {
            this.$message.warning('请输入定时更新配置')
            return
          }
          const {data} = await setCookieRefresh(this.productNameKey, this.cookieVal)
          this.msgSuccess("修改定时更新配置成功");
          this.showCookie = false;
        }catch (e) {
          console.log(e)
        }
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        Object.keys(row).map(item => {
          this.form[item] = row[item]
        })
        console.log(this.form)
        this.open = true;
        this.title = "设置";
      },
      handleConfig(row){
          this.showConfig = true;
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
        })
          .then(({value}) => {
            resetUserPwd(row.userId, value).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功，新密码是：" + value);
              }
            });
          })
          .catch(() => {
          });
      },
      /** 提交按钮 */
      submitForm: function () {
        console.log(this.form)
        this.$refs["form"].validate((valid) => {
          if (valid) {
            if (this.title === '设置') {
              updateClient(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("设置成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              addClient(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.id || this.ids;
        this.$confirm(
          '是否确认删除数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delUser(userIds);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {
          });
      },
      updateUserCookie (row) {
        if(this.productName == 'junglescout') {
          updateUserCookie(this.productId, {productId: this.productId, productUserIds: row.id}).then(() => {
            this.msgSuccess("刷新JS网页COOKIE成功");
          }).catch(() => {})
          return
        }else if(this.productName == 'merchantwords'){
          updateUserCookieM(this.productId, {productId: this.productId, productUserIds: row.id}).then(() => {
            this.msgSuccess("刷新魔词COOKIE成功");
          }).catch(() => {})
          return
        }else if(this.productName == '卖家精灵'){
          updateUserCookieElves(row.id).then(() => {
            this.msgSuccess("刷新卖家精灵COOKIE成功");
          }).catch(() => {})
          return
        }else{
          updateUserCookieJsPlugin(this.productId, {productId: this.productId, productUserIds: row.id}).then(() => {
             this.msgSuccess("刷新JS PLUGIN COOKIE成功");
          }).catch(() => {})
        }

      }
    },
  };
</script>
